function hasClass(element, cls) {
  return element.classList.contains(cls)
}

function addMatch(matched, node) {
  if (node.nodeType !== Node.TEXT_NODE) {
    if (node.className.match(/lsg-/)) {
      matched.push(node)
    }
  }
}

function addNextElement(selection, matched, i) {
  var j = i + 1;
  while (j < selection.length) {
    if (hasClass(selection[j], "lsg-headline")) {
      break;
    }
    addMatch(matched, selection[j])
    j++;
  }
}

function addPreviousElement(selection, matched, i) {
  var j = i
  while (j >= 0) {
    addMatch(matched, selection[j])
    if (hasClass(selection[j], "lsg-headline")) {
      break
    }
    j--
  }
}

document.addEventListener("DOMContentLoaded", function() {

  document.querySelector(".lsg-search-box").addEventListener("input", function(event) {
    var searchTerm = this.value

    var selection = document.querySelectorAll(".lsg-example, .lsg-color-swatches, .lsg-font-example, .lsg-paragraph, .lsg-unordered-list, .lsg-ordered-list, .lsg-headline, .lsg-sub-headline, .lsg-sub-sub-headline")
    var regexp = new RegExp(searchTerm, "i")
    selection = Array.prototype.slice.call(selection)
    var matched = []
    var unmatched = []

    for (var i = 0; i < selection.length; i++) {
      if (selection[i].textContent.match(regexp)) {
        addMatch(matched, selection[i])
        addNextElement(selection, matched, i)
        addPreviousElement(selection, matched, i)
      }
    }

    unmatched = selection.filter(function(element) {
      return matched.indexOf(element) === -1
    })

    unmatched.map(function(item) {
      item.style.display = "none"
    })

    matched.map(function(item) {
      item.style.display = "block"
    })
  })
})
